{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n"
     ]
    }
   ],
   "source": [
    "#Problem 1-1\n",
    "import math\n",
    "def isPrime(num):\n",
    "    #判断num是不是质数\n",
    "    if num==1:\n",
    "        return False\n",
    "    elif num==2:\n",
    "        return True\n",
    "    else:\n",
    "        for i in range(2,int(math.sqrt(num))+1):\n",
    "            if num % i == 0:\n",
    "                return False;\n",
    "        return True\n",
    "\n",
    "if __name__=='__main__':\n",
    "    primes = [ num for num in range(1,100) if isPrime(num)]\n",
    "    print(primes)        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'student0': 89, 'student1': 67, 'student2': 85, 'student3': 90, 'student4': 100, 'student5': 68, 'student6': 71, 'student7': 72, 'student8': 80, 'student9': 74, 'student10': 65, 'student11': 78, 'student12': 93, 'student13': 68, 'student14': 68, 'student15': 87, 'student16': 93, 'student17': 75, 'student18': 82, 'student19': 63}\n",
      "{'student3': 90, 'student4': 100, 'student12': 93, 'student16': 93}\n"
     ]
    }
   ],
   "source": [
    "#Problem 1-2——字典生成式\n",
    "import random\n",
    "studentInfo={f'student{i}':random.randint(60,100) for i in range(20)} #存放学生信息\n",
    "print(studentInfo)\n",
    "\n",
    "print({name:score for name,score in studentInfo.items() if score >=90})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "name: John, age: 22, gender: m, height: 170, weight: 65 (normal)\n",
      "name: Tommy, score: math-80 phys-90 chem-95, average: 88.3\n"
     ]
    }
   ],
   "source": [
    "#Problem 1-3\n",
    "class Person(object):\n",
    "    def __init__(self, name, age, gender, height=175, weight=65):\n",
    "        self.__name=name\n",
    "        self._age=age\n",
    "        self._gender=gender\n",
    "        self._height=height\n",
    "        self._weight=weight \n",
    "    def setName(self,name):\n",
    "        self.__name=name\n",
    "    def getName(self):\n",
    "        return self.__name\n",
    "    def bmi(self):\n",
    "        return (self._height-80)*0.7 if self._gender=='m' else (self._height-70)*0.6\n",
    "    def weightInfo(self):\n",
    "        if self._weight<0.9*self.bmi():\n",
    "            return 'underweight'\n",
    "        elif self._weight>1.1*self.bmi():\n",
    "            return 'overweight'\n",
    "        else:\n",
    "            return 'normal'\n",
    "    def __repr__(self):\n",
    "         return f'name: {self.__name}, age: {self._age}, gender: {self._gender}, height: {self._height}, weight: {self._weight} ({self.weightInfo()})'\n",
    "\n",
    "class Student(Person): \n",
    "    def __init__(self, name, age, gender, height, weight, score=[60,60,60]):\n",
    "        super().__init__(name, age, gender, height, weight)\n",
    "        self._score=score\n",
    "    def average(self):\n",
    "        return sum(self._score)/len(self._score)\n",
    "    def __repr__(self):\n",
    "         return f'name: {self.getName()}, score: math-{self._score[0]} phys-{self._score[1]} chem-{self._score[2]}, average: {self.average():.1f}'\n",
    "\n",
    "        \n",
    "if __name__=='__main__':\n",
    "    p1 = Person('John', 22, 'm', 170, 65) \n",
    "    print(p1)\n",
    "    p2 = Student('Tommy', 23, 'm', 175, 70, [80, 90, 95]) \n",
    "    print(p2)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "v1 + v2 = <3, 5, 7, 9, 11>\n",
      "v1 * v2 = 70\n",
      "v1.norm(\"2\") = 9.486832980505138\n",
      "v1.norm(\"1\") = 20\n",
      "v1.norm(\"inf\") = 6\n"
     ]
    }
   ],
   "source": [
    "#Problem 1-4\n",
    "import math\n",
    "class Vector(object):\n",
    "    def __init__(self,d):\n",
    "        if isinstance(d,int):\n",
    "            self._coords=[0]*d\n",
    "        elif isinstance(d,list):\n",
    "            self._coords=d\n",
    "    \n",
    "    def __len__(self):\n",
    "        return len(self._coords)\n",
    "    def __getitem__(self,n):\n",
    "        return self._coords[n]\n",
    "    def __setitem__(self,n,val):\n",
    "        self._coords[n]=val\n",
    "        \n",
    "    def __add__(self,other):\n",
    "        if len(self)!=len(other):\n",
    "            raise ValueError('Dimensions must agree')\n",
    "        result = Vector(len(self))\n",
    "        for n in range(len(self)):\n",
    "            result._coords[n]=self._coords[n]+other._coords[n]\n",
    "        return result\n",
    "    def __mul__(self,other):\n",
    "        if len(self)!=len(other):\n",
    "            raise ValueError('Dimensions must agree')\n",
    "        tmp = Vector(len(self))\n",
    "        for n in range(len(self)):\n",
    "            tmp._coords[n]=self._coords[n]*other._coords[n]\n",
    "        result=sum(tmp._coords)\n",
    "        return result\n",
    "    \n",
    "    def norm(self,mode=\"2\"):\n",
    "        if mode==\"1\":\n",
    "            return sum(self._coords)\n",
    "        elif mode==\"2\":\n",
    "            return math.sqrt(self*self)\n",
    "        elif mode==\"inf\":\n",
    "            return max(self._coords)\n",
    "    \n",
    "    def __repr__(self):\n",
    "        return f'<{str(self._coords)[1:-1]}>'\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    v1 = Vector([2, 3, 4, 5, 6])\n",
    "    v2 = Vector([1, 2, 3, 4, 5])\n",
    "    print(f'v1 + v2 = {v1 + v2}')\n",
    "    print(f'v1 * v2 = {v1 * v2}')\n",
    "    print(f'v1.norm(\"2\") = {v1.norm()}')\n",
    "    print(f'v1.norm(\"1\") = {v1.norm(\"1\")}')\n",
    "    print(f'v1.norm(\"inf\") = {v1.norm(\"inf\")}')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "#Problem 2-1\n",
    "def binary_search(data,target):\n",
    "    return binary_search_recur(data,target,0,len(data)-1) \n",
    "def binary_search_recur(data,target,low,high):\n",
    "    if low>high:\n",
    "        return False\n",
    "    else:\n",
    "        mid =(low+high)//2\n",
    "        if target==data[mid]:\n",
    "            return True\n",
    "        elif target<data[mid]:\n",
    "            return binary_search_recur(data,target,low,mid-1)\n",
    "        else:\n",
    "            return binary_search_recur(data,target,mid+1,high)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    data=[1,3,5,7,9]\n",
    "    print(binary_search(data,10))\n",
    "    print(binary_search(data,3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n",
      "[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n"
     ]
    }
   ],
   "source": [
    "#Problem 2-2\n",
    "def bad_fibonacci(n):\n",
    "    if n<=1:\n",
    "        return n\n",
    "    else:\n",
    "        return bad_fibonacci(n-1)+bad_fibonacci(n-2)\n",
    "def good_fibonacci(n):\n",
    "    if n<=1:\n",
    "        return (n,0)\n",
    "    else:\n",
    "        (a,b)=good_fibonacci(n-1)\n",
    "        return (a+b,a)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    print([bad_fibonacci(n) for n in range(10)])\n",
    "    print([good_fibonacci(n)[0] for n in range(10)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.5\n",
      "2.283333333333333\n"
     ]
    }
   ],
   "source": [
    "#Problem 2-3\n",
    "def harmonic(n):\n",
    "    if n==1:\n",
    "        return 1;\n",
    "    else:\n",
    "        return harmonic(n-1)+1/n;\n",
    "    \n",
    "if __name__=='__main__':\n",
    "    print(harmonic(2))\n",
    "    print(harmonic(5))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "snap&stop\n"
     ]
    }
   ],
   "source": [
    "#Problem 2-4\n",
    "def reverse(s):\n",
    "    if s == '':\n",
    "        return s;\n",
    "    else:\n",
    "        return reverse(s[1:]) + s[0];\n",
    "\n",
    "if __name__=='__main__':\n",
    "    print(reverse('pots&pans'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "32\n"
     ]
    }
   ],
   "source": [
    "#Problem 2-5\n",
    "def power(x,n):\n",
    "    if n == 0:\n",
    "        return 1\n",
    "    else:\n",
    "        partial = power(x,n//2)\n",
    "        result = partial*partial\n",
    "        if n % 2 == 1:\n",
    "            result *= x\n",
    "        return result\n",
    "\n",
    "if __name__=='__main__':\n",
    "    print(power(2,5))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
